import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaForm
} from 'comsMobx';
import {
	WeaLocaleProvider,
} from 'ecCom';
import {
	Button,
} from 'antd';
const getLabel = WeaLocaleProvider.getLabel;

export default class SearchStore {
	constructor(api, rootStore) {
		this.api = api;
		this.rootStore = rootStore;
	}

	get buttons(){
		return [getLabel(82529, '搜索'), getLabel(27088, '重置'), getLabel(32694, '取消')];
	}

	get searchProps() {
		return {
			advanceHeight: 130,
			hasMask: false,
			keyParam: 'key',
			searchType: ['base', 'advanced'],
			onChange: key => this.setSelectedKey(key),
			setShowSearchAd: bool => this.setShowSearchAd(bool),
			onSearch: () => this.onSearch(),
			onSearchChange: val =>  this.onSearchChange(val),
			buttonsAd: this.buttons.map((name, index) => {
				const type = (index === 0) && "primary";
				let callback;
				if (index === 0) {
					callback = () =>  this.onSearch();
				} else if (index === 1) {
					callback = () =>  this.form.reset();
				} else {
					callback = () => this.setShowSearchAd(false)
				}
				return <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nurpo5@${index}`} type={type} onClick={() => callback()}>{name}</Button>
			})
		}
	}

	linkageFieldName;

	@observable showSearchAd = false;
	@observable form = new WeaForm();
	@observable selectedKey = '';
	@observable datas = [];

	@computed get searchsAd() {
		return <div
			onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.onSearch()}
		>{this.form.render()}</div>;
	}

	@computed get baseValue() {
		return this.form.getFormParams()[this.linkageFieldName];
	}

	@action fetchSearch = (params = {}) => {
		return this.api.fetchSearch(params).then(datas => {
			const conditions = this.getCondition(datas);
			this.form.setCondition(conditions);
		});
	}

	@action setShowSearchAd = (bool) => {
		this.showSearchAd = bool;
	}

	@action onSearch = () => {
		this.rootStore.fetchTableList();
		this.setShowSearchAd(false);
	}

	@action onSearchChange = (val) => {
		if (this.linkageFieldName) {
			this.form.updateFields({
				[this.linkageFieldName]: val
			});
		}
	}

	@action setTabDatas = (datas) => {
		this.datas = datas;
	}

	@action setSelectedKey = (key) => {
		this.selectedKey = key;
	}

	setLinkageFieldName = (name) => {
		this.linkageFieldName = name;
	}

	getCondition = (datas) => {
		let c = [];
		Object.keys(datas).forEach(key => {
			if (key.includes('cdition')) {
				c = datas[key];
			}
		})
		return c;
	}
}